<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )

  edit-form(
    v-bind="editFormProps"
  )
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type EditFormProps,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { useQuery } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import { type TubeEntity, type TubeQueryParams } from "@scmt/api-lis-tube";
import colortag from "./colortag.vue";
import avatarUploader from "./avatar-uploader.vue";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<TubeQueryParams>({
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<null | TubeEntity>(null);

const { query, data, loadingMap } = useQuery({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.tube.query(params);
  },
  save: (model: TubeEntity) => {
    return $api.lis.tube.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      query("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.tube.destroy(ids).then(() => {
      $notify.success("删除成功");

      query("tableData", {
        pageSize: 20,
      });
    });
  },
  tubeColor: () => {
    return $api.dict.item.listAsOptions("tube_color");
  },
  listAsOptions: () => {
    return $api.lis.specimen.category.listAsOptions();
  },
  collectionMethod: () => {
    return $api.dict.item.listAsOptions("collection_method");
  },
});

onMounted(() => {
  query("tableData");
  query("tubeColor");
  query("listAsOptions");
  query("collectionMethod");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "name",
      label: "试管名称",
    },
  ];

  const headerActions: Action[] = ["add"];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => query("tableData"),
    onAct: onPageActions,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "index",
        label: "序号",
        width: "60px",
      },
      {
        prop: "imgUrl",
        label: "容器",
        render: ({ row }) => {
          if (row.imgUrl) {
            let srcList: any[] = [];
            srcList.push(row.imgUrl);
            return h(
              "div",
              h(resolveComponent("el-image"), {
                style: "width: 80px; height: 80px",
                src: row.imgUrl,
                previewSrcList: srcList,
                fit: "fill",
                zIndex: 20000,
                previewTeleported: true,
              })
            );
          } else {
            return h("span", row.imgUrl);
          }
        },
      },
      {
        prop: "name",
        label: "试管名称",
      },
      {
        prop: "color",
        label: "试管颜色",
        width: 90,
        render: ({ row }) => {
          const patientType = data.tubeColor ?? [];
          let resText = row.color;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter((item) => item.value == row.color);
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h(
            "div",
            {
              style: { background: row.color, textAlign: "center" },
            },
            resText
          );
        },
      },
      {
        prop: "specs",
        label: "规格",
      },
      {
        prop: "specimenTypeId",
        label: "标本类型",
        render: ({ row }) => {
          const patientType = data.listAsOptions ?? [];
          let resText = row.specimenTypeId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.specimenTypeId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "bloodCollectionVolume",
        label: "标本量",
      },
      {
        prop: "additive",
        label: "添加剂",
      },
      {
        prop: "collectionMethod",
        label: "采集方式",
        render: ({ row }) => {
          const patientType = data.collectionMethod ?? [];
          let resText = row.collectionMethod;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.collectionMethod
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "mainPurpose",
        label: "主要用途",
        tooltip: true,
      },
      {
        prop: "preparationProcess",
        label: "制备步骤",
        tooltip: true,
      },
      {
        label: "操作",
        actions: ["edit", "destroy"],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) => query("tableData", pagination),
    cellStyle: ({ row, column }) => {
      if (column.property === "color") {
        return { background: row.color };
      }
    },
  };
  return tableProps;
});

const editFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "name",
      label: "试管名称",
      required: true,
    },
    {
      prop: "color",
      label: "颜色",
      required: false,
      render: () => {
        return h(colortag, {
          modelValue: editingObj.value?.color,
          "onUpdate:modelValue": (val) => {
            Object.assign(editingObj.value, { color: val });
          },
        });
      },
    },
    {
      prop: "specs",
      label: "规格",
      required: false,
    },
    {
      prop: "specimenTypeId",
      label: "标本类型",
      as: "select",
      options: {
        loadMethod: () => $api.lis.specimen.category.listAsOptions(),
      },
    },
    {
      prop: "bloodCollectionVolume",
      label: "标本量",
      required: true,
    },
    {
      prop: "additive",
      label: "添加剂",
      required: false,
    },
    {
      prop: "mainPurpose",
      label: "主要用途",
    },
    {
      prop: "preparationProcess",
      label: "制备步骤",
    },
    {
      prop: "collectionMethod",
      label: "采集方式",
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("collection_method"),
      },
    },
    {
      prop: "remark",
      label: "备注",
    },
    {
      prop: "imgUrl",
      label: "容器",
      required: true,
      render: () =>
        h(avatarUploader, {
          modelValue: editingObj.value?.imgUrl,
          "onModel-value-update": (value: string) => {
            if (editingObj.value) {
              editingObj.value = Object.assign(editingObj.value, {
                imgUrl: value,
              });
            }
          },
        }),
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    loading: loadingMap.save,
    columns: 2,
    size: "middle",
    onClose: () => {
      editingObj.value = null;
    },
    onCancel: () => {
      editingObj.value = null;
    },
    onValidate: (model) => {
      query("save", model);
    },
  };

  return editProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.tube.$$createEntity(model);
      break;
    case "destroy":
      query("destroy", model ? model.id : "");

      break;
  }
};
</script>

<style lang="less" scoped></style>
